package com.hltx.service.redis.impl;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hltx.constants.RedisConstant;
import com.hltx.service.redis.JedisClusterUtil;

import redis.clients.jedis.JedisCluster;

public class JedisClusterService implements JedisClusterUtil{

	protected Logger logger = LoggerFactory.getLogger(JedisClusterUtil.class);
	
	@Autowired
    private JedisCluster jedisCluster;
	
	@Override
	public boolean lock(String key, long timeout, int expire) {
		long nanoTime = System.nanoTime();
		timeout = nanoTime + timeout * RedisConstant.MILLI_NANO_TIME;
		try{
			
			while(System.nanoTime() < timeout){
				if(jedisCluster.setnx(key, key) == 1){
					jedisCluster.expire(key, expire);
					return true;
				}
				logger.info("出现锁等待:"+key);
				Thread.sleep(3, new Random().nextInt(30));
			}
			
		}catch(Exception e){
			logger.info("获取锁错误"+key);
		}
		
		
		return false;
	}

	@Override
	public void unlock(String key) {
		try{
			jedisCluster.del(key);
		}catch(Exception e){
			logger.info("删除锁错误"+key);
		}
		
	}
	
}
